import * as bm from "/js/baseModule.js";
// var Swiper = require("/js/swiper.min.js");
let auiPullToRefresh = require('/js/auiPullToRefresh.js');

export class Module extends bm.baseModule {
    constructor(view) {
        super(view);
        let that = this;
        that._vote_supplier = 0;
        that._me_cnt = 0;
        that._total_cnt = 0;
        this._loadMoreBottom = false;
        this.defaultOption = {
            city: 'mine',
            demand: 'all',
            business: 'all'
        };
        that._moreDamenaVue = new Vue({
            el: $('.get-more-demand')[0],
            data: {
                me_cnt: that._me_cnt,
                total_cnt: that._total_cnt,
            },
        });
        new Vue({
            el: "#ProjectList-container",
            data: {
                items: globalData.project_list,
                vote_supplier: that._vote_supplier,
                selected_province: globalData.selPos.prov,
            },
            methods: {
                updateTime: function (startTime) {
                    return funs.countTimeGap(startTime)
                },
                callStop: function (phone, event) {
                    event.stopPropagation();    //  阻止事件冒泡
                    // tomato.getVPresenter<FromWPH>(funs.moduleToUrl('m/grab/FromWPH'), (FromWPH) => {
                    //     FromWPH.callPhone(phone);
                    //     tdom.open(FromWPH, tdom.DialogTarget.Blank, {
                    //         size: { width: '90%', height: tomato.DialogSize.Content },
                    //         effect: tdom.DialogEffect.scale,
                    //         masked: true
                    //     });
                    // })
                }
            }
        });
        this._moreLoading = this.find(".pull-more");
        this._outerScroller = this.find(".outerScroller");

        if (globalData.entryPage == 'index') {
            funs.removeWelcome();
        }
        let pullRefresh = new auiPullToRefresh({
            container: document.querySelector('.aui-refresh-content'),
            triggerDistance: 100,
            jQElement: $("#ProjectList")
        }, function (ret) {
            if (ret.status == "success") {
                //刷新回调
                that.loadMore();
                pullRefresh.cancelLoading(); //刷新成功后调用此方法隐藏
            }
        });

        // let swiper = new Swiper('.swiper-container', {
        //     autoplay: {
        //         delay: 5000,//1秒切换一次
        //         disableOnInteraction: false,//用户操作后，依旧保持自动滚动
        //     },
        //     loop : true,
        // });

        //请求头部数据
        that.getTodayCnt();
    }

    // index.js,用户信息回来后再调用此方法
    init() {
        let that = this;
        let provData = {
            sort: "published_at",//发布时间
            order: "desc",
            cnt: 20,
            city: 'mine',
            business: 'all',
            demand: 'all'
        };
        //如果是进入“我参与的”
        if (globalData.particalList) {
            that.defaultOption = {
                city: 'all',
                demand: 'mine',
                business: 'all'
            };
            that.find('.js-city .choice-val').text('全国');
            that.find('.js-demand .choice-val').text('我参与的');
        }
        //如果是游客
        if (globalData.user.user_type != '100') {
            that.defaultOption = {
                city: 'all',
                demand: 'all',
                business: 'all'
            };
            that.find('.js-city .choice-val').text('全国');
            that.find('.js-demand .choice-val').text('全部项目');
        }
        //如果是从“免费订单”链接进入的
        if (globalData.freeList) {
            that.find('.js-city .choice-val').text('全国');
            that.find('.js-demand .choice-val').text('免费订单');
            that.defaultOption = {
                city: 'all',
                demand: 'free',
                business: 'all'
            };
        }
        $.extend(true, provData, that.defaultOption);
        api.getDemandList(provData, {
            succ: function (proList) {
                globalData.project_list.length = 0;
                globalData.project_list.push(...proList);

                // 移除loading
                that.find('.pull-more').addClass("hide");

                // 监听下拉加载
                let div = that.view.get(0);
                that.view.scroll(function () {
                    let maxScroll = div.scrollHeight - div.offsetHeight;
                    if (div.scrollTop > maxScroll - 10 && !this._loadMoreBottom) {
                        that.scrollMore();
                    }
                });
            }
        });
    }
    _evt_toUserLevel() {
        if (globalData.user.user_type == 0) {
            funs.openModal('modules/modals/CommonModal.JS', function (mod) {
                mod.setType(1);
            })
        } else {
            location.hash = 'user/VipLevel';
        }
    }

    /**项目的点击事件 */
    _evt_projectDetail(obj) {
        let id = $(obj).attr('did');
        let pro_info = this.getProjectData(id);
        if (pro_info) {
            globalData.current_demand = pro_info;
            globalData.current_demand.bronze_partic_info = {
                'id': 0,  // 工程商（用户）id
                'id_': 0,  // 工程商（用户）id
                'nickname': '',  // 昵称
                'hide_nickname': '',
                'mobile': '', // 参与工程商手机,
                'follow_type': 0,//1 - 锁定 2-继续跟进 3-取消跟进
                'status': 0
            };

            if (pro_info.partic_demand_status == '9' || pro_info.is_training) {
                location.hash = 'DispatchDemand?did=' + id;
            } else {
                location.hash = 'DemandDetail?did=' + id;
            }
        }
    }

    /**获取单个项目的详细信息 */
    getProjectData(did) {
        for (var i = 0; i < globalData.project_list.length; i++) {
            if (globalData.project_list[i].id == did) {
                return globalData.project_list[i];
            }
        }
    }

    /**获取头部数据：_me_cnt与我相关的需求数量，_total_cnt今天的需求总数 */
    getTodayCnt() {
        let that = this;
        api.getTodayCnt({}, {
            succ: function (json) {
                that._moreDamenaVue.me_cnt = json.me_cnt;
                that._moreDamenaVue.total_cnt = json.total_cnt;
            },
            fail: function (error) {
                if (error.name == '41009002') {
                    //不是工程商
                    window.location.href = '/index.html';
                } else {
                    funs.tip(error.name, error.message, "fail");
                }
            }
        }
        );
    }

    /**加载更多 */
    loadMore(option) {
        let that = this;
        //请求头部数据
        this.getTodayCnt();
        if (this._loadMore) {
            return;
        }
        this._loadMore = true;
        this._moreLoading.removeClass("hide");
        let next = () => {
            this._loadMore = false;
            this._moreLoading.addClass("hide");
            this.find(".promptBar").removeClass('hide');
            this._outerScroller.scrollTop(0);
            setTimeout(() => {
                this.find('.promptBar').addClass('hide');
            }, 3000);
        }
        let plist = globalData.project_list;
        let sort_val;
        if (plist.length == 0) {
            sort_val = "";
        } else {
            sort_val = plist[0].published_at;
        }
        let options = { "sort_val": sort_val };
        //如果有option，则是筛选条件调用的方法；没有则是下拉刷新
        if (option) {
            api.getDemandListDesc(that.defaultOption, {
                succ: function (data) {
                    let newList = data;
                    //替换数据
                    globalData.project_list.length = 0;
                    globalData.project_list.push(...newList);

                    if (newList.length != 0) {
                        that.find(".promptBar").text('项目列表已更新');
                    } else {
                        that.find(".promptBar").text("当前设置下无项目");
                    }

                    // 缓存项目列表
                    let prolist = globalData.project_list;
                    prolist = JSON.stringify(prolist);
                    localStorage.setItem("prolist", prolist);
                    next();
                },
                fail: () => {
                    setTimeout(next, 3000);
                }
            });
        } else {
            $.extend(options, this.defaultOption);
            api.getDemandList(options, {
                succ: function (data) {
                    let newList = data;
                    if (newList.length != 0) {
                        that.find(".promptBar").text("更新了" + newList.length + "条新状态");
                        //向前插入数据
                        newList.reverse();
                        globalData.project_list.unshift(...newList);
                        setTimeout(next, 1000);
                        // 缓存项目列表
                        let prolist = globalData.project_list;
                        prolist = JSON.stringify(prolist);
                        localStorage.setItem("prolist", prolist);
                    } else {
                        that.find(".promptBar").text("暂无更新");
                        setTimeout(next, 1000);
                    }
                },
                fail: () => {
                    setTimeout(next, 3000);
                }
            });
        }

    }

    scrollMore() {
        let that = this;
        if (this._loadMoreBottom) {
            return;
        }
        this._loadMoreBottom = true;
        this.find('.scroll .downMore').removeClass("hide");
        let plist = globalData.project_list;
        let sort_val;
        if (plist.length == 0) {
            return
        } else {
            sort_val = plist[plist.length - 1].published_at;
        }
        let options = funs.deepCopy(this.defaultOption);
        options["sort_val"] = sort_val;
        api.getDemandListDesc(options, {
            succ: function (data) {
                let newList = data;
                if (newList.length != 0) {
                    //向后插入数据
                    globalData.project_list.push(...newList);
                    // 缓存项目列表
                    let prolist = globalData.project_list;
                    prolist = JSON.stringify(prolist);
                    localStorage.setItem("prolist", prolist);
                    that._loadMoreBottom = false;
                    that.find('.downMore').addClass("hide");
                } else {
                    setTimeout(function () {
                        that.find('.scroll .downMore').addClass("hide");
                        that.find('.noMore').show();
                    }, 500);
                }
            },
            fail: function (error) {
                that._loadMoreBottom = false;
                this.find('.scroll .downMore').addClass("hide");
                funs.tip(error.msg, '', 'fail');
            }
        });
    }

    //城市选择的结果导入，并刷新列表
    setCity(city) {
        this.defaultOption.city = city;
        this.loadMore(true);
        let cityText = city;
        if (cityText.length > 4) {
            cityText = cityText.substr(0, 3) + '…';
        }
        this.find('.js-city .choice-val').text(cityText);
    }

    _evt_loadSetService() {
        location.hash = 'user/SetService';
    }

    /** ========= 首页项目列表筛选条件-start ===========*/
    _evt_openChoice(obj) {
        // ======= 动画效果 =======
        let icon = $(obj).find('.icon-circle-down');
        let index = $(obj).index('.dropBtn .col-xs-4');
        let choicePane = $('.choice-pane');
        // 为了动画效果的完美，故判断；否则可以toggle简洁的实现的；
        if (icon.hasClass('rotate')) {
            choicePane.slideToggle();
            setTimeout(function () {
                choicePane.find('ul').eq(index).toggle();
            }, 500);

        } else {
            //在已经打开的情况下，切换大选项类
            if ($('.dropBtn').find('.rotate').length > 0) {
                $(obj).siblings().find('span').removeClass('rotate');
                choicePane.find('ul').hide();
                choicePane.find('ul').eq(index).toggle();
            } else {
                choicePane.find('ul').eq(index).toggle();
                choicePane.slideToggle();
            }

        }
        icon.toggleClass('rotate');

    }

    _evt_chooseFilter(obj, hit) {
        //点击后收起筛选框
        let choicePane = $('.choice-pane');
        if (obj == hit) {
            choicePane.slideToggle();
            $('.dropBtn').find('.rotate').removeClass('rotate');
            setTimeout(function () {
                choicePane.find('ul').hide();
            }, 500);
            return
        }
        choicePane.slideToggle();
        $('.dropBtn').find('.rotate').removeClass('rotate');
        let index = $(hit).parent('ul').index('.choice-pane>ul');
        $('.dropBtn').find('.choice-val').eq(index).text($(hit).text().trim().substr(0, 4));
        setTimeout(function () {
            choicePane.find('ul').hide();
        }, 500);

        // 点击了某个筛选条件
        let arr = $(hit).attr('con').split('@');
        // 如果选择了指定城市，则是打开城市选择
        if (arr[1] == 'none') {
            location.hash = 'project/SelProvDemand';
            return
        }
        //如果是游客/客户点击了需要登录的选项
        if (arr[1] == 'mine' && globalData.user.user_type != 100) {
            let type = 1;
            if (globalData.user.user_type == 1) {
                type = 2;
            }
            $(document).trigger('openLoginModal', [false, type]);
            return
        }

        //其他条件则是取到配置项，获取新的list
        let option = {};
        option[arr[0]] = arr[1];
        $.extend(this.defaultOption, option);
        this.loadMore(option);
    }

    //无项目页面 查看更多项目
    _evt_checkMoreDemand() {
        let option = {
            city: 'all',
            demand: 'all',
            business: 'all'
        };
        $.extend(this.defaultOption, option);
        this.loadMore(option);
        //修改文案
        this.find('.js-city .choice-val').text('全国');
        this.find('.js-business .choice-val').text('全部类型');
        this.find('.js-demand .choice-val').text('全部项目');
    }

    _evt_goFollowWx() {
        location.hash = 'project/FollowWx';
    }
}